<?php
if (!(defined('IN_IA')))
{
    exit('Access Denied');
}
/**
 * User: 邓志锋 <280160522@qq.com> <http://www.diygw.com>
 * Date: 2018-07-28
 * Time: 下午 6:06
 */
class Pay_Diygwcom extends DiygwcomAction
{
    public function index()
    {

        global $_GPC, $_W;
        $orderid = safe_gpc_string($_GPC['id']);

        $order = pdo_get(getTableName('order'), array('id'=>$orderid), array('id','order_id','dashboard_id', 'status','pay_title','pay_price'));

        if(empty($order)){
            message('支付订单不存在！', $this->createMobileUrl('home_index', array('m'=>'diygwcom_app')), 'error');
        }
        $_GPC['dashboardid']=$order['dashboard_id'];
        if($order['status']==0){
            message('订单已取消！', $this->createMobileUrl('home_index', array('m'=>'diygwcom_app')), 'error');

        }else if($order['status']==1){
            $orderinfos  = pdo_getall(getTableName('order_info'),array('order_id'=>$order['id']));
            foreach ($orderinfos as $key=>$item){
                $linkjson = json_decode($item['link_json'],true);
                $tablename=$linkjson['tablename'];
                $sqlfields =$linkjson['sqlfields'];
                $sql="select $sqlfields from ims_$tablename where id=:id ";
                $link =pdo_fetch($sql,array(":id"=> safe_gpc_string($item['link_id'])));


                if(false===$link){
                    return $this->getErrorMessage($link['link_title']."商品已下架");
                }
                if(empty($link['stock'])){
                    return $this->getErrorMessage($link['link_title']."库存不足");
                }
                if(safe_gpc_int($link['stock'])<safe_gpc_int($item['link_total'])){
                    return $this->getErrorMessage($link['link_title']."库存不足");
                }
            }

            /*if(!$this->inMobile || empty($_W['openid'])) {
                $message="打开微信扫一扫二维码完成支付";
                include $this->template('pay/weixin');
                return;
            }*/

            $uid = MODULE_DEBUG?1:$_W['fans']['uid'];
            $orderpay["pay_type"]="0";
            $orderpay["pay_title"]=$order['pay_title'];
            $orderpay["pay_time"]=date("Y-m-d H:i:s", time());
            $orderpay["trade_no"]=DiygwcomUtil::create_guid();
            $orderpay["pay_price"]=$order['pay_price'];
            $orderpay["order_id"]=$order['id'];
            $orderpay["user_id"]=$uid;
            $orderpay["openid"]=$_W['openid'];
            $orderpay["status"]="1";
            pdo_insert(getTableName("order_pay"),$orderpay);
            //构造支付请求中的参数
            $params = array(
                'tid' =>$orderpay["trade_no"],    //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
                'ordersn' =>$orderpay["trade_no"],//收银台中显示的订单号
                'title' => $order['pay_title'],   //收银台中显示的标题
                'fee' => $order['pay_price'],     //收银台中显示需要支付的金额,只能大于 0
                'user' => $_W['fans']['uid'],     //付款用户, 付款的用户名(选填项)
            );

            //调用pay方法
            $this->pay($params);
        }else{
            if($order['status']==2){
                $message="订单已付款待发货！";
            }else if($order['status']==3){
                $message="订单待收货！";
            }else if($order['status']==4){
                $message="交易完成！";
            }
            $dashboardid = $order["dashboard_id"];
            $extendValues = $this->getDashboardExtends($dashboardid);
            $params = array(
                'message' =>'订单已付款待发货！',//收银台中显示的订单号
                'title' => $order['pay_title'],   //收银台中显示的标题
                'fee' => $order['pay_price'],     //收银台中显示需要支付的金额,只能大于 0
                'user' => $_W['fans']['uid'],     //付款用户, 付款的用户名(选填项)
            );
            include $this->template('pay/paymessage');
        }
    }

    protected function pay($params = array(), $mine = array()) {
        global $_W,$_GPC;
        $title=$params['title'];
        load()->model('activity');
        load()->model('module');
        activity_coupon_type_init();

        $dashboardid = $_GPC["dashboardid"];
        $extendValues = $this->getDashboardExtends($dashboardid);


        $params['module'] =MODULE_NAME;
        if($params['fee'] <= 0) {
            $pars = array();
            $pars['from'] = 'return';
            $pars['result'] = 'success';
            $pars['type'] = '';
            $pars['tid'] = $params['tid'];
            $site = WeUtility::createModuleSite($params['module']);
            $method = 'payResult';
            if (method_exists($site, $method)) {
                exit($site->$method($pars));
            }
        }
        $log = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => $params['module'], 'tid' => $params['tid']));
        if (empty($log)) {
            $log = array(
                'uniacid' => $_W['uniacid'],
                'acid' => $_W['acid'],
                'openid' => $_W['member']['uid'],
                'module' => MODULE_NAME,
                'tid' => $params['tid'],
                'fee' => $params['fee'],
                'card_fee' => $params['fee'],
                'status' => '0',
                'is_usecard' => '0',
            );
            pdo_insert('core_paylog', $log);
        }
        if($log['status'] == '1') {
            message('这个订单已经支付成功, 不需要重复支付.', '', 'info');
        }
        $setting = uni_setting($_W['uniacid'], array('payment', 'creditbehaviors'));
        if(!is_array($setting['payment'])) {
            message('没有有效的支付方式, 请联系网站管理员.', '', 'error');
        }
        $pay = $setting['payment'];
        $we7_coupon_info = module_fetch('we7_coupon');
        if (!empty($we7_coupon_info)) {
            $cards = activity_paycenter_coupon_available();
            if (!empty($cards)) {
                foreach ($cards as $key => &$val) {
                    if ($val['type'] == '1') {
                        $val['discount_cn'] = sprintf("%.2f", $params['fee'] * (1 - $val['extra']['discount'] * 0.01));
                        $coupon[$key] = $val;
                    } else {
                        $val['discount_cn'] = sprintf("%.2f", $val['extra']['reduce_cost'] * 0.01);
                        $token[$key] = $val;
                        if ($log['fee'] < $val['extra']['least_cost'] * 0.01) {
                            unset($token[$key]);
                        }
                    }
                    unset($val['icon']);
                    unset($val['description']);
                }
            }
            $cards_str = json_encode($cards);
        }
        if (empty($_W['member']['uid'])) {
            $pay['credit']['switch'] = false;
        }
        if ($params['module'] == 'paycenter') {
            $pay['delivery']['switch'] = false;
            $pay['line']['switch'] = false;
        }
        if (!empty($pay['credit']['switch'])) {
            $credtis = mc_credit_fetch($_W['member']['uid']);
            $credit_pay_setting = mc_fetch($_W['member']['uid'], array('pay_password'));
            $credit_pay_setting = $credit_pay_setting['pay_password'];
        }
        $you = 0;
        include $this->template('pay/paycenter');
    }


    public function payResult($params)
    {
        global $_W;
        $msg = '支付成功';
        $orderpayresult = pdo_get(getTableName('order_pay'), array('trade_no' => $params['tid']), array('id','order_id', 'status', 'openid','pay_title'));
        $order = pdo_get(getTableName('order'), array('id' => $orderpayresult['order_id']), array('dashboard_id'));
        //根据参数params中的result来判断支付是否成功
        if ($params['result'] == 'success' ) {
            // 支付成功，改变订单状态并提示支付成功消息
            if ($orderpayresult['status'] ==1){
                try{
                    $orderpay = array(
                        'uniontid'	=> $params['uniontid'],
                        'pay_type'		=> $params['type'],
                        'payment'	=> $params['fee'],
                        'status'		=> 2,
                        'pay_end_time'	=> date('Y-m-d H:i:s', TIMESTAMP)
                    );
                    //如果是微信支付，需要记录transaction_id。
                    if ($params['type'] == 'wechat') {
                        $orderpay['transaction_id'] = $params['tag']['transaction_id'];
                    }
                    pdo()->begin();
                    $result = pdo_update(getTableName('order_pay'), $orderpay, array('trade_no' => $params['tid']));
                    $orderarray = array(
                        'trade_no'	=> $orderpay['transaction_id'],
                        'order_pay_id'		=> $orderpayresult['id'],
                        'status'		=> 2,
                        'pay_time'	=> date('Y-m-d H:i:s', TIMESTAMP)
                    );
                    $result = pdo_update(getTableName('order'), $orderarray, array('id' => $orderpayresult['order_id']));
                    if(false===$result) {
                        $msg = '支付成功，但订单状态更改失败！';
                    }else{
                        $msg='支付成功';
                    }
                    // 操作成功则提交更改
                    pdo()->commit();
                    $log = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => MODULE_NAME , 'tid' => $params['tid']));

                    // 发送文本消息提醒
                    $text = '您的订单：'.$orderpayresult['pay_title']."\n订单号：".$log['uniontid']."\n";
                    $custom = array(
                        'msgtype' => 'text',
                        'text' => array('content' => urlencode($text.$msg)),
                        'touser' => $orderpayresult['openid'],
                    );

                    $account_api = WeAccount::create();
                    $result = $account_api->sendCustomNotice($custom);
                } catch (Exception $e){
                    // 失败回滚
                    pdo()->rollback();
                    //var_dump($e);
                }

            }
        }else {
            // 支付失败
            $msg = '支付失败';
            message($msg, $this->createMobileUrl('pay_index', array('id'=>$orderpayresult['order_id'])), 'error' );
        }

        // 后台通知
        if($params['from'] == 'notify'){
            // 发送文本消息提醒
            // $text = '您的订单：'.$order_info['title']."\n订单号：".$params['tid']."\n";
            // $custom = array(
            //     'msgtype' => 'text',
            //     'text' => array('content' => urlencode($text.$msg)),
            //     'touser' => $params['user'],
            // );
            // $account_api = WeAccount::create();
            // $result = $account_api->sendCustomNotice($custom);
            // message($msg, $project['back_url'], 'success' );
        }
        //因为支付完成通知有两种方式 notify，return,notify为后台通知,return为前台通知，需要给用户展示提示信息
        //return做为通知是不稳定的，用户很可能直接关闭页面，所以状态变更以notify为准
        //如果消息是用户直接返回（非通知），则提示一个付款成功
        //如果是JS版的支付此处的跳转则没有意义
        if ($params['from'] == 'return') {

            $homepageid= pdo_get(getTableName('PAGE'), array('dashboard_id'=>$order['dashboard_id'],'is_home'=>'1','template'=>'mobile'), array('id'));
            if($homepageid){
                $homePage=DiygwcomUtil::to_mobile_url($this->createMobileUrl('page_index', array('m'=>'diygwcom_app','pid'=>$homepageid['id'])));
                message($msg, $homePage, 'success' );
            }else{
                message($msg, "", 'success' );
            }
            // $result = $account_api->sendCustomNotice($custom);
            //message($msg, $project['back_url'], 'success' );
        }
    }

}